package com.test.multithread.deadlock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.TimeUnit;

public class AvoidDeadlockExample {
    private final Lock lockA = new ReentrantLock();
    private final Lock lockB = new ReentrantLock();

    public void methodA() throws InterruptedException {
        try {
            lockA.lockInterruptibly();
            TimeUnit.SECONDS.sleep(1); // 模拟长时间任务
            lockB.lockInterruptibly();
            // 执行业务逻辑
        } finally {
            lockB.unlock();
            lockA.unlock();
        }
    }

    public void methodB() throws InterruptedException {
        try {
            lockB.lockInterruptibly();
            TimeUnit.SECONDS.sleep(1); // 模拟长时间任务
            lockA.lockInterruptibly();
            // 执行业务逻辑
        } finally {
            lockA.unlock();
            lockB.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        AvoidDeadlockExample example = new AvoidDeadlockExample();
        Thread thread1 = new Thread(() -> {
            try {
                example.methodA();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupted();
                System.out.println("线程1被中断");
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                example.methodB();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupted();
                System.out.println("线程2被中断");
            }
        });

        thread1.start();
        thread2.start();

        // 主线程等待一段时间后中断子线程
        TimeUnit.SECONDS.sleep(2);
        thread1.interrupt();
        thread2.interrupt();

        thread1.join();
        thread2.join();
    }
}